package controller

import (
	"MessageSendService/app/common/log"
	"MessageSendService/app/core/rpc"
	"MessageSendService/app/core/rpc/proto"
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"strconv"
	"time"
)

func InitRouter() {
	r := gin.New()

	r.Use(corsMiddleware())
	r.Use(ginLogger(log.GetZapOriginLogger())) //设置gin的log为自定义的logger
	r.Use(gin.Recovery())

	//接收触发的定时任务，发送消息
	r.POST("/run/:id", Run)

	err := r.Run(":8099")
	if err != nil {
		panic(err)
	}
}

//接收触发的定时任务，发送消息
// @Summary 接收触发的定时任务，发送消息

func Run(c *gin.Context) {
	templateIdString := c.Param("id")
	templateId, err := strconv.ParseInt(templateIdString, 10, 64)
	if err != nil {
		log.GetLogger().Error("获取模版id失败", zap.Error(err))
		c.JSON(500, gin.H{
			"error": err,
		})
		return
	}
	messageParam := proto.MessageParam{
		Extra:     nil,
		Receiver:  "+8618319178738，+8619810792500",
		Variables: nil,
	}
	fmt.Println(templateId)
	//现在模拟直接发送短信消息
	messageRequest := proto.MessageRequest{
		Code:              "",
		MessageParam:      &messageParam,
		MessageTemplateId: templateId,
	}
	fmt.Println(messageRequest)
	message, err := rpc.Client.SendMessage(context.Background(), &messageRequest)
	if err != nil {
		log.GetLogger().Error("rpc调用失败", zap.Error(err))
		c.JSON(500, gin.H{
			"error": err,
		})
		return
	}
	log.GetLogger().Info("rpc调用成功", zap.Any("message", message))
	c.JSON(200, gin.H{})
}

// 自定义的CORS中间件
func corsMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	}
}

// GinLogger 接收gin框架默认的日志
func ginLogger(logger *zap.Logger) gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path
		query := c.Request.URL.RawQuery
		c.Next()

		cost := time.Since(start)
		logger.Info(path,
			zap.Int("status", c.Writer.Status()),
			zap.String("method", c.Request.Method),
			zap.String("path", path),
			zap.String("query", query),
			zap.String("ip", c.ClientIP()),
			zap.String("user-agent", c.Request.UserAgent()),
			zap.String("errors", c.Errors.ByType(gin.ErrorTypePrivate).String()),
			zap.Duration("cost", cost),
		)
	}
}
